<template>
  <div class="root">
    <el-card>
      <!-- 头部 -->
      <el-header>
        <el-row type="flex">
          <el-col>
            <el-button
              type="primary"
              @click="isShowDialog = true"
            >新增</el-button>
          </el-col>
          <el-col :span="10">
            <el-select
              v-model="getListConfig.agent_contains"
              :clearable="true"
              placeholder="请选择"
            >
              <el-option
                v-for="item in agentList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-col>
          <el-col :span="10">
            <el-select
              v-model="getListConfig.category_contains"
              :clearable="true"
              placeholder="请选择"
            >
              <el-option
                v-for="item in categoryList"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              />
            </el-select>
          </el-col>
          <el-col>
            <el-input
              v-model="getListConfig.title_contains"
              placeholder="请输入内容"
              class="input-with-select"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="searchFn"
              />
            </el-input>
          </el-col>
        </el-row>
      </el-header>
      <!-- 表格 -->
      <transition name="fade-transform" mode="out-in">
        <el-table v-show="isshow" :data="buildingList" border="">
          <!-- 表头排序功能,接口有问题,不做 -->
          <!-- <el-table :data="buildingList" border="" @header-click="headerClick"> -->
          <el-table-column label="封面">
            <template v-slot="{ row }">
              <img :src="row.image" alt="" height="100px">
            </template>
          </el-table-column>
          <el-table-column label="标题" prop="title" />
          <el-table-column label="标签" prop="tags">
            <template v-slot="{ row }">
              <el-tag v-for="(item, index) in row.tags" :key="index">{{
                item
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="地址" prop="address" />
          <el-table-column label="经纪" prop="agent.name" />
          <el-table-column label="类型" prop="category.title" />
          <el-table-column label="价格" prop="price">
            <template slot="header"> 价格<i class="el-icon-sort-up" /> </template>
          </el-table-column>
          <el-table-column label="介绍" prop="desc" />
          <el-table-column label="图片">
            <template v-slot="{ row }">
              <img :src="row.photos && row.photos[0]" alt="" height="100px">
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template v-slot="{ row }">
              <el-button type="primary" @click="edtFn(row.id)">编辑</el-button>
              <el-button type="danger" @click="delFn(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </transition>
      <!-- 弹出框 -->
      <el-dialog
        ref="dialogCom"
        :visible="isShowDialog"
        title="房产管理"
        center
        @close="btnCan"
      >
        <!-- el-form绑定数据model和校验规则rule -->
        <!-- el-form-item绑定prop属性 -->
        <el-form
          ref="dialogForm"
          :model="formData"
          :rules="rules"
          label-width="80px"
        >
          <!-- 下拉框 -->
          <el-form-item label="经纪" prop="agent">
            <el-select v-model="formData.agent">
              <el-option
                v-for="item in agentList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="分类" prop="category">
            <el-select v-model="formData.category">
              <el-option
                v-for="item in categoryList"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <!-- 输入框 -->
          <el-form-item label="标题" prop="title">
            <!-- el-input v--model双向绑定 -->
            <el-input v-model="formData.title" />
          </el-form-item>
          <el-form-item label="描述" prop="desc">
            <el-input v-model="formData.desc" />
          </el-form-item>
          <el-form-item label="价钱" prop="price">
            <el-input v-model="formData.price" />
          </el-form-item>
          <!-- 标签 -->
          <el-form-item label="标签">
            <el-tag
              v-for="tag in formData.tags"
              :key="tag"
              closable
              :disable-transitions="false"
              @close="handleClose(tag)"
            >
              {{ tag }}
            </el-tag>
            <el-input
              v-if="inputVisible"
              ref="saveTagInput"
              v-model="inputValue"
              class="input-new-tag"
              size="small"
              @keyup.enter.native="handleInputConfirm"
              @blur="handleInputConfirm"
            />
            <el-button
              v-else
              class="button-new-tag"
              size="small"
              @click="showInput"
            >
              + 新增标签</el-button>
          </el-form-item>
          <!-- 高德接口 层级选择器 -->
          <el-form-item label="区域" prop="area">
            <!-- <el-input v-model="formData.address" /> -->
            <el-cascader
              v-model="value"
              placeholder="请选择省市区"
              :options="distList"
              :props="{
                children: 'districts',
                label: 'name',
                value: 'name',
              }"
              @change="handleChange"
            />
          </el-form-item>
          <el-form-item label="详细地址" prop="address">
            <el-input v-model="formData.address" />
          </el-form-item>
          <!-- 富文本框 -->
          <el-form-item label="内容">
            <template>
              <vue-editor v-model="formData.content" />
            </template>
          </el-form-item>
          <!-- 上传组件 单个 -->
          <el-form-item label="封面">
            <ImageUpload ref="imageUploadCom" :is-limit="true" />
          </el-form-item>
          <!-- 上传组件 多个 -->
          <el-form-item label="图片">
            <ImageUpload ref="imageUploadGroup" />
          </el-form-item>
        </el-form>
        <template v-slot:footer>
          <el-button @click="btnCan">取消</el-button>
          <el-button type="primary" @click="btnCfm">确定</el-button>
        </template>
      </el-dialog>
      <!-- 分页 -->
      <el-pagination
        hide-on-single-page
        layout="prev, pager, next"
        :total="total"
        :page-size="getListConfig._limit"
        :current-page="currentPage"
        @current-change="currentChange"
      />
    </el-card>
  </div>
</template>

<script>
// 引入组件
import ImageUpload from './component/imageUpload.vue'
// 引入地产接口
import {
  addBuilding,
  delBuilding,
  editBuilding,
  getBuildingCount,
  getBuildingDetailById,
  getBuildingList
} from '@/api/building'
// 引入经纪接口
import { getAgentList } from '@/api/agent'
// 引入分类接口
import { getCategories } from '@/api/classification'
// 引入高德接口
import { getMapDist } from '@/api/map'
export default {
  components: {
    ImageUpload
  },
  data() {
    return {
      isshow: true, // 切图特效
      buildingList: [], // 房产列表
      agentList: [], // 经纪列表
      distList: [], // 行政区列表
      categoryList: [], // 分类列表
      // 请求参数
      formData: {
        id: '', // 区分新增和编辑
        title: '',
        desc: '',
        image: '',
        agent: '',
        content: '',
        address: '',
        price: '',
        photos: {},
        tags: [],
        category: ''
      },
      // 校验规则
      rules: {
        agent: [{ required: true, message: '经纪不能为空', trigger: 'blur' }],
        category: [
          { required: true, message: '房屋类型不能为空', trigger: 'blur' }
        ],
        title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
        desc: [{ required: true, message: '描述不能为空', trigger: 'blur' }],
        price: [{ required: true, message: '价钱不能为空', trigger: 'blur' }],
        address: [{ required: true, message: '地址不能为空', trigger: 'blur' }]
      },
      isShowDialog: false, // 控制弹出框的展示
      inputVisible: false, // 标签是否展示
      inputValue: '', // 标签的值
      value: [], // 层级选择器的值
      getListConfig: {
        _limit: 2, // 限制条数
        _start: 0, // 从默认排序的第几个结果开始
        title_contains: '', // 搜索 标题
        agent_contains: '', // 搜索 中介
        category_contains: '' // 搜索 分类
        // _sort: null // 根据字段排序
      }, // 搜索条件配置
      total: 0, // 总条数
      currentPage: 1
    }
  },
  created() {
    // 房产列表
    this.getBuildingList()
    // 中介列表
    this.getAgentList()
    // 行政区域列表
    this.getMapDist()
    // 分类列表
    this.getCategoryList()
  },
  methods: {
    // 封装获取房产列表 初始化渲染
    async getBuildingList() {
      // 获取房产列表
      const { data } = await getBuildingList(this.getListConfig)
      // 获取房产总数
      const res = await getBuildingCount(this.getListConfig)
      this.buildingList = data // 房产列表
      this.total = res.data // 总条数
    },
    // 封装获取中介列表
    async getAgentList() {
      const { data } = await getAgentList()
      // 保存到全局
      this.agentList = data
    },
    // 封装获取分类列表
    async getCategoryList() {
      const { data } = await getCategories()
      this.categoryList = data
    },
    // 封装行政区域列表
    async getMapDist() {
      const { data } = await getMapDist({ subdistrict: 3 })
      console.log(245, data)
      const mapData = data.districts[0].districts
      // 遍历省
      mapData.forEach((provice) => {
        // 遍历市
        provice.districts.forEach((city) => {
          // 遍历区
          city.districts.forEach((dist) => {
            // 删除区底下的划分
            delete dist.districts
          })
        })
      })
      // 保存到全局
      this.distList = mapData
    },
    // 编辑按钮事件
    async edtFn(val) {
      // 调接口
      const { data } = await getBuildingDetailById(val)
      // 数据的回显
      this.formData = data
      // 接口小bug的处理
      // agent和category要字符串, 接口返回对象
      this.formData.agent = data.agent ? data.agent.id : ''
      this.formData.category = data.category ? data.category.id : ''
      // 把插槽的id保存到全局
      this.formData.id = val
      // 弹出模态框
      this.isShowDialog = true
      this.$nextTick(() => {
        // 封面回显
        if (this.formData.image) {
          this.$refs.imageUploadCom.fileList = [{ url: this.formData.image }]
        }
        // 图片回显
        if (this.formData.photos && this.formData.photos.length) {
          // 加工接口返回数组,根据fileList的格式
          this.$refs.imageUploadGroup.fileList = this.formData.photos.map(
            (item) => {
              return { url: item }
            }
          )
        }
      })
    },
    // 删除按钮事件
    async delFn(val) {
      // 二次确认
      await this.$confirm('确认删除?')
      // 调用删除接口
      await delBuilding(val)
      // 提示用户
      this.$message.success('删除成功')
      // 定义总页数
      const totalPage = Math.ceil(this.total / this.getListConfig._limit)
      // 判断是否是最后一页的最后一项,且不是第一页
      if (this.currentPage === totalPage && this.total % this.getListConfig._limit === 1 && this.currentPage > 1) {
        // 页数自减
        this.currentPage--
        // 重置起始页面
        this.getListConfig._start = this.getListConfig._limit * (this.currentPage - 1)
      }
      // 刷新页面
      this.getBuildingList()
    },
    // 模态框取消
    async btnCan() {
      // 清空校验
      await this.$refs.dialogForm.resetFields()
      // 重置表单
      this.formData = {
        id: '', // 区分新增和编辑
        title: '',
        desc: '',
        image: '',
        agent: '',
        content: '',
        address: '',
        price: '',
        photos: {},
        tags: [],
        category: ''
      }
      // 清空上传图片的数据
      this.$refs.imageUploadCom.fileList = []
      this.$refs.imageUploadGroup.fileList = []
      // 关闭模态框
      this.isShowDialog = false
    },
    // 模态框确定
    async btnCfm() {
      // 封面相关操作
      const fileList = this.$refs.imageUploadCom.fileList
      // 判断封面是否上传成功
      if (fileList[0] && fileList[0].status !== 'success') {
        // 提示用户
        this.$message.warning('请等待封面上传成功')
        // 退出
        return
      }
      // 将封面添加到formData表单
      this.formData.image = fileList[0] ? fileList[0].url : ''

      // 图片相关操作
      const fileListGroup = this.$refs.imageUploadGroup.fileList
      // 判断图片是否全部上传成功
      if (fileListGroup.find((item) => item.status !== 'success')) {
        // 提示用户
        this.$message.warning('请等待图片上传成功')
        // 退出
        return
      }
      if (fileListGroup.length) {
        // 将图片添加到formData表单
        this.formData.photos = fileListGroup.map((item) => item.url)
      }

      // 校验表单
      await this.$refs.dialogForm.validate()
      // 判断有无id,没有是新增,有是编辑
      if (this.formData.id) {
        // 调用编辑接口
        const res = await editBuilding(this.formData)
        console.log('编辑', res)
      } else {
        // 调用新增接口
        const res = await addBuilding(this.formData)
        console.log('新增', res)
        if (this.total % this.getListConfig._limit === 0) {
        // 总数除以每页显示数，取余为0，说明是最后一项,新页面整除后 +1
          const newPage = this.total / this.getListConfig._limit + 1
          // 0->0 1->2 2->4
          this.getListConfig._start = (newPage - 1) * this.getListConfig._limit
          // console.log('最后一项', this.getListConfig._start)
        } else {
        // 不是最后一项，则除后取天花板数
          const newPage = Math.ceil(this.total / this.getListConfig._limit)
          this.getListConfig._start = (newPage - 1) * this.getListConfig._limit
          // console.log('不是最后一项', this.getListConfig._start)
        }
      }
      // 提示用户
      this.$message.success('操作成功')
      // 重置表单
      this.formData = {
        id: '', // 区分新增和编辑
        title: '',
        desc: '',
        image: '',
        agent: '',
        content: '',
        address: '',
        price: '',
        photos: {},
        tags: [],
        category: ''
      }
      // 关闭模态框
      this.isShowDialog = false
      // 重新渲染
      await this.getBuildingList()
      // 重新给页面赋值
      this.currentPage = Math.ceil(this.total / this.getListConfig._limit)
    },
    // 删除标签el-tag
    handleClose(tag) {
      this.formData.tags.splice(this.formData.tags.indexOf(tag), 1)
      console.log('close')
    },
    // 编辑标签el-tag
    showInput() {
      console.log('show')
      this.inputVisible = true
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 新增标签el-tag
    handleInputConfirm() {
      console.log(confirm)
      const inputValue = this.inputValue
      if (inputValue) {
        this.formData.tags.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    // 层级选择器
    handleChange(value) {
      // 把区域地址添加到输入框
      this.formData.address = value.join('')
    },
    // 点击搜索按钮
    async searchFn() {
      // 结果从头开始
      this.getListConfig._start = ''
      // 重置页头
      this.currentPage = 1
      // 带搜索条件的地产列表
      this.getBuildingList()
    },
    // 点击分页
    currentChange(currentPage) {
      this.isshow = false // 切图特效
      setTimeout(() => {
        this.isshow = true
      }, 100)
      // 保存到全局
      this.currentPage = currentPage
      // 重置起始页面
      this.getListConfig._start = this.getListConfig._limit * (currentPage - 1)
      // 调用获取房产列表渲染接口
      this.getBuildingList()
    }
  }
}
</script>

<style lang="scss" scoped>
/* fade-transform */
.fade-transform-leave-active,
.fade-transform-enter-active {
  transition: all 0.1s;
}

.fade-transform-enter {
  opacity: 0;
  transform: translateX(-80px);
}

.fade-transform-leave-to {
  opacity: 0;
  transform: translateX(50px);
}
.root{
  margin-top: 20px;
  margin-left: 20px;
}
/* el-tag样式 */
::v-deep .el-tag + .el-tag {
  margin-left: 10px;
}
::v-deep .button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
::v-deep .input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
/* 头部输入框样式 */
// ::v-deep .el-select .el-input {
//   width: 130px;
// }
// ::v-deep .input-with-select .el-input-group__prepend {
//   background-color: #fff;
// }

</style>
